import React, { Component } from 'react'
import { Link, Route, Switch } from 'react-router-dom'
import { Layout, Menu } from 'antd'
import './Home.css'
import { MenuUnfoldOutlined, MenuFoldOutlined } from '@ant-design/icons'

import menuList from './HomeRouter'

const { Header, Sider, Content } = Layout
const { SubMenu } = Menu

export default class Home extends Component {
  state = {
    collapsed: false,
    menuList,
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    })
  }

  getMenuNodes = (data) => {
    return data.map((item) => {
      if (!item.children) {
        return (
          <Menu.Item key={item.path} icon={item.icon}>
            <Link className="list-group-item" to={item.path}>
              {item.name}
            </Link>
          </Menu.Item>
        )
      } else {
        return (
          <SubMenu key={item.path} icon={item.icon} title={item.name}>
            {this.getMenuNodes(item.children)}
          </SubMenu>
        )
      }
    })
  }

  getRouteNode = (data) => {
    return data.map((v) => {
      if (v.component) {
        return <Route path={v.path} component={v.component} key={v.path} />
      } else {
        return v.children.map((item) => {
          return (
            <Route
              path={item.path}
              component={item.component}
              key={item.path}
            />
          )
        })
      }
    })
  }

  render() {
    let cunrrentPath = this.props.location.pathname
    let { menuList } = this.state
    return (
      <Layout>
        <Sider trigger={null} collapsible collapsed={this.state.collapsed}>
          <Menu
            theme="dark"
            mode="inline"
            selectedKeys={[cunrrentPath]}
            defaultOpenKeys={['/home/systemyimiao']}
            defaultSelectedKeys={['/home/addYimiao']}
          >
            {this.getMenuNodes(menuList)}
          </Menu>
        </Sider>
        <Layout className="site-layout">
          <Header className="site-layout-background" style={{ padding: 0 }}>
            {React.createElement(
              this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined,
              {
                className: 'trigger',
                onClick: this.toggle,
              }
            )}
            <span style={{ fontSize: '30px' }}>REACT学习</span>
          </Header>
          <Content
            className="site-layout-background"
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
            }}
          >
            <Switch>{this.getRouteNode(menuList)}</Switch>
          </Content>
        </Layout>
      </Layout>
    )
  }
}
